var tablename = "notes";
var app = this;
var $ = require("../../include/$");
module.exports = {
	get: function(req, res) {
		var data = req.query;
		if (data.datatype) {
			delete data['datatype'];
			tablename = "notes"
			var finner = req.models[tablename].find(data, 20, ["createtime", "Z"]);
		} else {
			tablename = "notetype";
			var finner = req.models[tablename].find(data, 20);
		};
		console.log("查询表“", tablename, "”的数据", req.body, req.query);
		finner.run(function(err, result) {
			if (err) {
				res.send(500, err);
			} else if (!result.length) {
				res.send(404, "no found");
			} else {
				res.send(result);
				res.end();
			};
		})
	},
	post: function(req, res) {
		var data = req.body;
		if (data.datatype == 1) {
			delete data['datatype'];
			tablename = "notetype";
		} else {
			tablename = "notes";
			data.createtime = new Date().getTime();
		};
		console.log(data);
		req.models[tablename].create($.extend({}, data), function(err, result) {
			if (err) {
				res.send(500, err);
			} else {
				res.send("ok");
				console.log("success");
				res.end();
			};
		})
	},
	put: function(req, res) {
		var id = req.body.id;
		tablename = "notetype";
		console.log("为表“", tablename, "”进行修改：", req.body, req.query);
		req.models[tablename].get(id, function(err, result) {
			if (err) {
				res.send(500, err);
			} else {
				if (result.num) {
					result.num += 1
				} else {
					result.num = 1;
				};
				result.save(function(err) {
					if (err) {
						res.send(500, err);
					} else {
						res.send("ok");
						res.end();
					}
				});
			}
		});
	},
	delete: function(req, res) {
		req.models[tablename].get(req.body.id, function(err, result) {
			if (err) {
				res.send(500, err);
			} else {
				for (var id in result) {
					result.id = req.body.id;
				};
				result.remove(function(err) {
					if (err) {
						res.send(500, err);
					} else {
						// res.send(result);
						//返回新的数据列表
						res.end();
					}
				});
			}
		});
	}
}